<script lang="ts" setup>
import type { FormInstance } from '@arco-design/web-vue'
import { ClassInfoApi, ReportApi } from '@/apis'
import { useDictLabel, useForm } from '@/hooks'
import { getClassImage } from '@/utils/image'
import { Message } from '@arco-design/web-vue'

interface Props {
  classId: string
  simple?: boolean
}
const props = withDefaults(defineProps<Props>(), {
  classId: undefined,
  simple: false,
})
const formRef = ref<FormInstance>()
const { form } = useForm<ClassInfoApi.ClassUpdateReq>({
  name: undefined,
  classYear: undefined,
  term: undefined,
  grade: undefined,
  subject: undefined,
  classCategory: undefined,
  admissionYearLimit: undefined,
  classTypeId: undefined,
  campusId: undefined,
  classroomId: undefined,
  leadTeacherId: undefined,
  assistTeacherId: undefined,
  planStudentCount: undefined,
  prevClassId: undefined,
  lessonChangeLimit: undefined,
  saleStatus: undefined,
  totalPrice: undefined,
  unitPrice: undefined,
  renewalStartTime: undefined,
  renewalEndTime: undefined,
  enrollStartTime: undefined,
  lessonHourFactor: undefined,
  salePerformanceFactor: undefined,
})
const router = useRouter()

const loading = ref(false)
const readonly = ref(true)

const dataId = ref('')
const dataDetail = ref<ClassInfoApi.ClassDetailResp>()

const classStat = ref<ReportApi.ClassStat>()

const getClassBasicInfo = async () => {
  try {
    loading.value = true
    dataDetail.value = await ClassInfoApi.getClassDetail(dataId.value)
    for (const key in form) {
      form[key] = dataDetail.value?.[key]
    }
  } finally {
    loading.value = false
  }
}

const getClassStat = async () => {
  classStat.value = await ReportApi.getClassStatById(dataId.value)
}

const getDataDetail = async () => {
  getClassBasicInfo()
  getClassStat()
}

const onSave = async () => {
  // copyFields(form, data)
  try {
    await ClassInfoApi.updateClass(form, dataId.value)
    Message.success('修改成功')
    await getClassBasicInfo()
    readonly.value = true
  // eslint-disable-next-line unused-imports/no-unused-vars
  } catch (_) {}
}

// 班型
const onClassTypeSelect = (item) => {
  form.classLevelLimit = item.level
}

// 取消
const onCancel = () => {
  readonly.value = true
  for (const key in form) {
    form[key] = dataDetail.value?.[key]
  }
  formRef.value?.clearValidate()
}

const onEdit = async () => {
  readonly.value = false
}

onMounted(() => {
  // getDataDetail()
})

watchEffect(() => {
  if (props.classId) {
    dataId.value = props.classId
    getDataDetail()
  }
})

const collapsed = ref(false)
defineExpose({
  onSave,
})
</script>

<template>
  <a-spin class="w-full" :loading="loading">
    <a-page-header @back="router.back()">
      <template #title>
        <a-space>
          <CellDict :value="form.classCategory" code="ClassCategoryEnum" />
          <span v-if="readonly" class="max-w-500px font-size-16px color-black font-600">{{ form.name || '-' }}</span>
          <a-input v-else v-model="form.name" class="min-w-350px" placeholder="请输入班级名称" />
        </a-space>
      </template>
      <template #subtitle>
        <a-typography-text type="secondary" copyable>
          {{ dataId }}
        </a-typography-text>
      </template>
      <template #extra>
        <a-space>
          <a-tag color="gray">
            <template #icon>
              <span>满班率</span>
            </template>
            <div class="m-l-2">
              <span class="font-size-[18px] color-black font-600">{{ classStat?.fullRate}}</span>
              <span>%</span>
            </div>
          </a-tag>
          <a-tag color="gray">
            <template #icon>
              <span>续报率</span>
            </template>
            <div class="m-l-2">
              <span class="font-size-[18px] color-black font-600">{{ classStat?.renewalRate}}</span>
              <span>%</span>
            </div>
          </a-tag>
          <a-tag color="gray">
            <template #icon>
              <span>留存率</span>
            </template>
            <div class="m-l-2">
              <span class="font-size-[18px] color-black font-600">{{ classStat?.retainedRate}}</span>
              <span>%</span>
            </div>
          </a-tag>
          <!-- <a-tag color="gray">
            <template #icon>
              <span>课消费用</span>
            </template>
            <div class="m-l-2">
              <span class="font-size-[18px] color-black font-600">{{ lessonPrice?.totalPrice ? lessonPrice.totalPrice : 0 }}</span>
              <span>￥</span>
            </div>
          </a-tag> -->

          <ReadonlyEditButton
            v-permission="['edu:class:write']"
            :readonly="readonly"
            :deleteable="false"
            @edit="onEdit"
            @cancel="onCancel"
            @save="onSave"
          />

          <!-- <a-button type="primary" size="small" class="ml" @click="onEdit">
            <template #icon>
              <icon-edit v-if="readonly" />
              <icon-save v-else />
            </template>
            {{ readonly ? '编辑' : '保存' }}
          </a-button> -->
        </a-space>
      </template>
    </a-page-header>
    <a-space class="w-full">
      <a-tag color="orangered">
        <span class="mr-sm">招生进度</span>
        <a-progress color="orangered" :percent="dataDetail?.planStudentCount === 0 ? 0 : (dataDetail?.enrollStudentCount || 0) / (dataDetail?.planStudentCount || 0) " :steps="dataDetail?.planStudentCount" size="small">
          <template #text>
            {{ dataDetail?.enrollStudentCount || 0 }}/{{ dataDetail?.planStudentCount || 0 }}
          </template>
        </a-progress>
      </a-tag>

      <a-tag>
        <span class="mr-sm">课程进度</span>
        <a-progress :percent="dataDetail?.totalLessonCount === 0 ? 0 : (dataDetail?.completedLessonCount || 0) / (dataDetail?.totalLessonCount || 0)" :steps="dataDetail?.totalLessonCount" size="small">
          <template #text>
            {{ dataDetail?.completedLessonCount || 0 }}/{{ dataDetail?.totalLessonCount || 0 }}  {{ dataDetail?.arrangeTemplate.startDate }} ~ {{ dataDetail?.arrangeTemplate.endDate }}
          </template>
        </a-progress>
      </a-tag>
    </a-space>
    <a-divider margin="8px" />
    <a-form ref="formRef" :model="form" :readonly="readonly" auto-label-width size="small">
      <div class="mb-2 flex gap-5">
        <a-image
          width="190"
          height="136"
          :src="getClassImage(form.image)"
        />
        <div class="flex-1">
          <a-row :gutter="10">
            <readonly-form-item label="年份" :span="6" field="classYear">
              <template #readonly>
                <a-typography>
                  {{ dataDetail?.classYear }}/{{ useDictLabel('TermEnum', dataDetail?.term) }}
                </a-typography>
              </template>
              <YearTermCascader v-model:class-year="form.classYear" v-model:term="form.term" />
            </readonly-form-item>
            <readonly-form-item label="年级" :span="6" field="grade">
              <DictSelect v-model="form.grade" type="select" code="Grade" />
            </readonly-form-item>
            <readonly-form-item label="科目" :span="6" field="subject">
              <DictSelect v-model="form.subject" type="select" code="Subject" />
            </readonly-form-item>
            <readonly-form-item label="教室" :span="6" field="classroom" :editable="false">
              <a-typography>{{ dataDetail?.campusName }}/{{ dataDetail?.classroomName }}</a-typography>
            </readonly-form-item>
            <readonly-form-item label="主讲老师" :span="6" field="leadTeacherId" :editable="false">
              <a-typography>{{ dataDetail?.leadTeacherName }}</a-typography>
            </readonly-form-item>
            <readonly-form-item label="辅导老师" :span="6" field="assistTeacherId">
              <template #readonly>
                <a-typography>{{ dataDetail?.assistTeacherName || '--' }}</a-typography>
              </template>
              <EmployeeSelect v-model="form.assistTeacherId" type="ASSIST_TEACHER" placeholder="辅导老师" />
            </readonly-form-item>
            <readonly-form-item label="班型" :span="6" field="classTypeId">
              <template #readonly>
                <a-typography>{{ dataDetail?.classTypeName || '-' }}</a-typography>
              </template>
              <ClassTypeSelect v-model="form.classTypeId" @select="onClassTypeSelect" />
            </readonly-form-item>
            <readonly-form-item label="入学年份限制" :span="6" field="admissionYearLimit" tooltip="入学年份要求，超过当年则不限制">
              <YearPicker v-model="form.admissionYearLimit" />
              <!-- <a-year-picker v-model="form.admissionYearLimit" placeholder="请选择" /> -->
            </readonly-form-item>
            <readonly-form-item label="课时业绩系数" field="lessonHourFactor" :span="6">
              <a-input-number v-model="form.lessonHourFactor" mode="button" :step="0.1" :min="0" />
            </readonly-form-item>
            <readonly-form-item label="销售业绩系数" field="salePerformanceFactor" :span="6">
              <a-input-number v-model="form.salePerformanceFactor" mode="button" :step="0.1" :min="0" />
            </readonly-form-item>
            <readonly-form-item label="单价" :span="6" field="unitPrice">
              <a-input-number v-model="form.unitPrice" :min="0" placeholder="请输入单价" :hide-button="true">
                <template #append>
                  元
                </template>
              </a-input-number>
            </readonly-form-item>
            <readonly-form-item label="总价" :span="6" field="totalPrice">
              <a-input-number v-model="form.totalPrice" :min="0" placeholder="请输入总价" :hide-button="true">
                <template #append>
                  元
                </template>
              </a-input-number>
            </readonly-form-item>
            <readonly-form-item label="调课限制" :span="6" field="lessonChangeLimit">
              <a-input-number v-model="form.lessonChangeLimit" placeholder="调限次数" :hide-button="true" />
            </readonly-form-item>
            <readonly-form-item label="计划招生" :span="6" field="planStudentCount">
              <a-input-number v-model="form.planStudentCount" placeholder="计划招生人数" :hide-button="true" />
            </readonly-form-item>
            <readonly-form-item label="上架状态" :span="6" field="saleStatus">
              <DictSelect v-model="form.saleStatus" type="switch" code="SaleStatusEnum" />
            </readonly-form-item>
          </a-row>
        </div>
      </div>
      <a-row v-show="collapsed" :gutter="10">
        <a-alert v-if="form.enrollStartTime && form.renewalStartTime && form.renewalEndTime" :show-icon="false" class="mb">
          <a-timeline direction="horizontal" mode="bottom" label-position="same">
            <a-timeline-item :label="form.renewalStartTime" dot-color="#52C419">
              续报期开始，允许前序在读学员提前报名
            </a-timeline-item>
            <a-timeline-item :label="form.renewalEndTime" dot-color="#F5222D">
              续报期结束，不允许报名，仅允许调课转班
            </a-timeline-item>
            <a-timeline-item :label="form.enrollStartTime">
              开放报名，允许所有人报名
            </a-timeline-item>
          </a-timeline>
        </a-alert>
        <readonly-form-item label="续报期" :span="12" tooltip="续报期开始后允许当前在读学员提前报名，续报期结束后不允许提前报名，但允许调课转班">
          <template #readonly>
            <span class="text-gray-8">{{ (form.renewalStartTime && form.renewalEndTime) ? `${form.renewalStartTime}-${form.renewalEndTime}` : '-' }}</span>
          </template>
          <RangePicker v-model:from="form.renewalStartTime" v-model:to="form.renewalEndTime" show-time format="YYYY-MM-DD HH:mm" :placeholder="['续报开始时间', '续报结束时间']" />
        </readonly-form-item>
        <readonly-form-item label="开放报名时间" tooltip="该时间后允许所有人报名" :span="12">
          <template #readonly>
            <span class="text-gray-8">{{ form.enrollStartTime }}</span>
          </template>
          <a-date-picker
            v-model="form.enrollStartTime"
            class="w-full"
            show-time
            format="YYYY-MM-DD HH:mm"
            :time-picker-props="{ defaultValue: '08:00:00' }"
            placeholder="开放报名时间"
          />
        </readonly-form-item>
        <readonly-form-item label="描述" :span="24" field="description">
          <a-textarea v-model.trim="form.description" placeholder="请输入课程介绍" allow-clear :max-length="900" show-word-limit />
        </readonly-form-item>
      </a-row>
      <a-col :span="24">
        <a-divider :margin="10">
          <a-button type="text" size="small" @click="collapsed = !collapsed">
            {{ collapsed ? '收起' : '更多' }}
            <template #icon>
              <icon-up v-if="collapsed" />
              <icon-down v-else />
            </template>
          </a-button>
        </a-divider>
      </a-col>
    </a-form>
  </a-spin>
</template>

<style lang="less" scoped>
:deep(.arco-page-header) {
  position: sticky;
  top: 0;
  z-index: 2;
  background: #fff;
}
:deep(.arco-page-header-wrapper) {
  padding: 0;
}

:deep(.arco-form-item) {
  margin-bottom: 2px;
}
</style>
